﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Entity.Package;
using Entity.Table;
using System.Data;
using Tools;

namespace BLL.Business
{
    /// <summary>
    /// 缴费业务处理
    /// </summary>
    public class Payment
    {
        public static void ProcessPayment(PackRequestPayment payment,CSocket.ClientThread client)
        {
            PackFailReturn pkFailReturn = new PackFailReturn();
            pkFailReturn.TradeCode = ((int)TradeCode.缴费业务).ToString();
            try
            {
                string payDate = payment.PayDate.Trim();
                //再次验证扣款标志是否为0，是则允许交费
                if (Db.PaymentManager.IsPayment(payment.GasUserID.Trim(),payment.PackHead.BankWaterNumber.Trim())) //允许交费
                {
                    try
                    {
                        DataSet ds = Db.SearchInfoManager.GetPaymentInfoByUserID(payment.GasUserID.Trim(),
                                                                                   Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ZNJDays"].ToString()));
                        //应缴合计（滞纳金+欠费总金额）
                        decimal yjhj = decimal.Parse(ds.Tables[0].Rows[0]["YJHJ"].ToString());
                        decimal realMoney = decimal.Parse(payment.PayMoney.Trim());
                        if (realMoney < yjhj)
                        {
                            pkFailReturn.ResponseCode = ((int)ResponseCode.金额不符).ToString().PadLeft(3, '0');
                            pkFailReturn.PackHead = new PackHead(payment.PackHead.PayWay, payment.PackHead.BankWaterNumber, (Encoding.Default.GetBytes(pkFailReturn.ToString()).Length).ToString());
                            CSocket.PackageHandle.SendFailurPackage(pkFailReturn, client);

                            LogHelper.WriteInfoLog(string.Format("{0}缴费失败,实缴金额小于应缴金额，不允许缴费！", payment.GasUserID.Trim()));
                            return;
                        }
                        decimal jbAccountBalance = decimal.Parse(ds.Tables[0].Rows[0]["AccountBalance"].ToString()) + realMoney - decimal.Parse(ds.Tables[0].Rows[0]["OwnFeeMoney"].ToString()) - decimal.Parse(ds.Tables[0].Rows[0]["ZNJ"].ToString());
                        string payWayName = "";
                        switch (payment.PackHead.PayWay.Trim())
                        {
                            case "01":
                                payWayName = "银行柜台";
                                break;
                            case "02":
                                payWayName = "批量代扣";
                                break;
                            case "03":
                                payWayName = "自助终端";
                                break;
                            case "04":
                                payWayName = "电话银行";
                                break;
                            case "05":
                                payWayName = "网上银行";
                                break;
                            case "06":
                                payWayName = "手机银行";
                                break;
                        }

                        int jtZGQL = 0;
                        decimal kbJieYu = 0;
                        StepPrice.StepPriceInfo info = null;
                        if (ds.Tables[0].Rows[0]["MeterType"].ToString() == "1") //是卡表则计算阶梯
                        {
                            info = Common.CalueStepInfo(payment.GasUserID.Trim(), decimal.Parse(payment.PayMoney.Trim()), out jtZGQL, out kbJieYu);
                        }
                        decimal currentJieYu = ds.Tables[0].Rows[0]["MeterType"].ToString() == "1" ? kbJieYu : jbAccountBalance;
                        string businessdate = payDate.Substring(0, 4) + "-" + payDate.Substring(4, 2) + "-" + payDate.Substring(6, 2) + " " +
                                  payDate.Substring(8, 2) + ":" + payDate.Substring(10, 2) + ":" + payDate.Substring(12, 2);
                        MPayment entityPay = new MPayment(payment.GasUserID.Trim(), "NXS", businessdate,
                                                         payment.OperatorNumber.Trim(), payment.PackHead.BankWaterNumber,
                                                         double.Parse(payment.PayMoney.Trim()),
                                                         payment.PackHead.PayWay.Trim(),
                                                         currentJieYu,
                                                         payWayName,
                                                         info == null ? 0 : info.Price1,
                                                         info == null ? 0 : Convert.ToInt32(info.Gas1),
                                                         info == null ? 0 : info.Money1,
                                                         info == null ? 0 : info.Price2,
                                                         info == null ? 0 : Convert.ToInt32(info.Gas2),
                                                         info == null ? 0 : info.Money2,
                                                         info == null ? 0 : info.Price3,
                                                         info == null ? 0 : Convert.ToInt32(info.Gas3),
                                                         info == null ? 0 : info.Money3,
                                                         jtZGQL + (info == null ? 0 : Convert.ToInt32(info.Gas1)),
                                                         info == null ? 0 : Convert.ToInt32(info.PayGas));

                        if (Db.PaymentManager.Insert(entityPay)) //缴费成功                    
                        {
                            PackReturnPaymentSuccess pkPayReturn = new PackReturnPaymentSuccess();
                            pkPayReturn.TradeCode = ((int)TradeCode.缴费业务).ToString();

                            //组织正常返回包
                            pkPayReturn.ResponseCode = ((int)ResponseCode.交易成功).ToString().PadLeft(3, '0');
                            pkPayReturn.OwnFeeMoney = ds.Tables[0].Rows[0]["OwnFeeMoney"].ToString();
                            pkPayReturn.GasUserID = payment.GasUserID.ToString();
                            pkPayReturn.UserName = ds.Tables[0].Rows[0]["UserName"].ToString();
                            pkPayReturn.Address = ds.Tables[0].Rows[0]["Address"].ToString();
                            pkPayReturn.LastYE = ds.Tables[0].Rows[0]["AccountBalance"].ToString();
                            pkPayReturn.UserProperties = "0";
                            pkPayReturn.AccountBalance = currentJieYu.ToString();
                            pkPayReturn.PayMoney = payment.PayMoney;
                            pkPayReturn.CbRecordTimes = "0";
                            pkPayReturn.PackHead = new PackHead(payment.PackHead.PayWay, payment.PackHead.BankWaterNumber, (Encoding.Default.GetBytes(pkPayReturn.ToString()).Length - 1).ToString());
                            byte[] sendPackage = CSocket.PackageHandle.CombinationPackage(pkPayReturn);
                            if (client.Send(sendPackage))  //发送返回包
                                client.CloseSocket();//断开链接

                            LogHelper.WriteInfoLog(string.Format(@"交费成功！【编号{0}；银行代码{1}；日期{2}；操作员ID{3}; 流水号{4}; 交费金额{5}; 交费方式{6}；
                                                  新结余{7}；交费方式名称{8}】", entityPay.GasUserID, entityPay.BankCode, entityPay.BusinessDate,
                                                                  entityPay.OperatorID, entityPay.BankWaterNumber, entityPay.PayMoney, entityPay.PayWay, entityPay.CurrentJY, entityPay.PayWayName));
                        }
                        else  //缴费失败
                        {
                            Db.PaymentManager.UpdateFlag(payment.GasUserID);
                            //组织失败返回包
                            pkFailReturn.ResponseCode = ((int)ResponseCode.交易失败).ToString().PadLeft(3, '0');
                            pkFailReturn.PackHead = new PackHead(payment.PackHead.PayWay, payment.PackHead.BankWaterNumber, (Encoding.Default.GetBytes(pkFailReturn.ToString()).Length).ToString());

                            CSocket.PackageHandle.SendFailurPackage(pkFailReturn, client);

                            LogHelper.WriteInfoLog(string.Format(@"交费失败！【编号{0}；银行代码{1}；日期{2}；操作员ID{3}; 流水号{4}; 交费金额{5}; 交费方式{6}；
                                                  新结余{7}；交费方式名称{8}】", entityPay.GasUserID, entityPay.BankCode, entityPay.BusinessDate,
                                                                 entityPay.OperatorID, entityPay.BankWaterNumber, entityPay.PayMoney, entityPay.PayWay, entityPay.CurrentJY, entityPay.PayWayName));
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteErrorLog("ProcessPayment方法-缴费业务出现异常：" + ex.Message,ex);
                        Db.PaymentManager.UpdateFlag(payment.GasUserID);

                        pkFailReturn.ResponseCode = ((int)ResponseCode.其他错误).ToString().PadLeft(3, '0');
                        pkFailReturn.PackHead = new PackHead(payment.PackHead.PayWay, payment.PackHead.BankWaterNumber, (Encoding.Default.GetBytes(pkFailReturn.ToString()).Length).ToString());
                        CSocket.PackageHandle.SendFailurPackage(pkFailReturn, client);
                    }
                }
                else //不允许交费
                {
                    Db.PaymentManager.UpdateFlag(payment.GasUserID);
                    pkFailReturn.ResponseCode = ((int)ResponseCode.特殊用户不能在银行缴费).ToString().PadLeft(3, '0');
                    pkFailReturn.PackHead = new PackHead(payment.PackHead.PayWay, payment.PackHead.BankWaterNumber, (Encoding.Default.GetBytes(pkFailReturn.ToString()).Length).ToString());
                    CSocket.PackageHandle.SendFailurPackage(pkFailReturn, client);
                    LogHelper.WriteInfoLog(string.Format("{0}缴费无效！", payment.GasUserID.Trim()));
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog("ProcessPayment方法-缴费业务出现异常：" + ex.Message, ex);
                pkFailReturn.ResponseCode = ((int)ResponseCode.数据库操作错).ToString().PadLeft(3, '0');
                pkFailReturn.PackHead = new PackHead(payment.PackHead.PayWay, payment.PackHead.BankWaterNumber, (Encoding.Default.GetBytes(pkFailReturn.ToString()).Length).ToString());
                CSocket.PackageHandle.SendFailurPackage(pkFailReturn, client);
            }
        }
    }
}
